package com.ibp.service.impl;

import com.ibp.comparator.ComparatorSRM;
import com.ibp.controller.SysRunManageController;
import com.ibp.dao.DictDataMapper;
import com.ibp.entity.SysRunManage;
import com.ibp.service.DictDataService;
import com.ibp.service.ExecuteCmdService;
import com.ibp.service.FSHttpService;
import com.ibp.service.SysRunManageService;
import com.ibp.utils.SocketClientUtils;
import com.ibp.utils.StringUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("sysRunManageServiceImpl")
public class SysRunManageServiceImpl implements SysRunManageService, InitializingBean{

  private static Logger logger = LoggerFactory.getLogger(SysRunManageController.class);	

  private String ibms_ip = null;
  private String ibms_port = null;
  private String ibms_session = null;
  private String url = null;

  private ServletContext servletContext;
  
  @Autowired
  FSHttpService fSHttpServiceImpl;
  @Autowired
  DictDataMapper dictDataMapper;
  @Autowired
  DictDataService dictDataServiceImpl;
  @Autowired
  ExecuteCmdService executeCmdServiceImpl;


  
  /***
   * 执行cmd命令获取注册中心的基本信息
   */
  @Override
  public Map<String,Object> getIbmsInfo(String cmd) {
	  Map<String,Object> map = new HashMap<String,Object>();
      String response = executeCmdServiceImpl.executeIbmsCmdData(cmd);
      map.put("ibmsUrl", getIbmsUrl(this.ibms_ip + ":" + this.ibms_port));
      map.put("ibmsStatus", getIbmsStatus("ibms.sh status \n"));
      map.put("console", response);
	  return map;
  }
  
  
  /***
   *  获取系统运行管理界面数据 
   */
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public Map getSysRunManage(SysRunManage srm){
    Map map = new HashMap();
    List<SysRunManage> data = getSessions("ibma");
    map.put("data", data);
    return map;
  }

  /**
   * 获取注册中心页面数据
   */
  @SuppressWarnings("unchecked")
public Map getRegistryList(SysRunManage srm){
    Map<String,Object> map = new HashMap<String,Object>();
    List<SysRunManage> data = getSessions();
    //过滤
    filter(data,srm);
    //排序
    Collections.sort(data,new ComparatorSRM());
    map.put("data", data);
    return map;
  }

  
  /***
   * 过滤结果集
   * @param list
   * @param srm
   * @return
   */
  public List<SysRunManage> filter(List<SysRunManage> list , SysRunManage srm){
	  if(srm != null){
		  String regex_sn = String2Regex(srm.getSessionNode()) ;
		  String regex_ra = String2Regex(srm.getRemoteAdress());
		  for(Iterator<SysRunManage> it = list.iterator();it.hasNext();){
			  SysRunManage s = it.next() ;
			  if((StringUtil.isEmpty(regex_sn) ? true : (StringUtil.isEmpty(s.getSessionNode()) ? false : s.getSessionNode().matches(regex_sn)) ) 
					  && (StringUtil.isEmpty(regex_ra) ? true : (StringUtil.isEmpty(s.getRemoteAdress()) ? false : s.getRemoteAdress().matches(regex_ra)))){
				  continue ;
			  }else{
				  it.remove();
			  }
		  }
	  }
	  return list ; 
  }
  
  
  /***
   * 根据输入的查询条件生成正则表达式
   * '*' -- 表示匹配任意字符
   * '?' --匹配一个字符 
   * @param str
   * @return
   */
  protected String String2Regex(String str) {
	  if(StringUtil.isEmpty(str)){
		  return null ;
	  }
	  return str.replaceAll("\\.", "\\.")
				  .replaceAll("\\*", ".*")
				  .replaceAll("\\?", ".{1}")
				  .replaceAll("\\(", "\\\\(")
				  .replaceAll("\\)", "\\\\)");
	}
  
  
  /**
   * 解析http请求返回的报文
   * @param response
   * @return
   */
  protected List<SysRunManage> parseResponse(String response){
    if ((response == null) || ("".equals(response))) {
      return null;
    }
    Map<String,Map<String,String>> dicMap = (Map<String, Map<String, String>>) servletContext.getAttribute("dictMap");
    String[] res = response.split("[\n]+");
    List list = new ArrayList();
    for (int i = 0; i < res.length; ++i) {
      String[] s = res[i].split("[ ]+");
      SysRunManage srm = new SysRunManage();
      for (int j = 0; j < s.length; ++j) {
        switch (j)
        {
        case 0:
          srm.setLocalAdress(s[j]);
          break;
        case 1:
          srm.setSessionType(s[j]);
          srm.setSessionTypeName(dicMap.get("ibpType").get(s[j]));
          break;
        case 2:
          srm.setSessionNode(s[j]);
          break;
        case 3:
          srm.setRemoteAdress(s[j]);
          break;
        case 4:
          srm.setIbmaLocalAddress(s[j]);
        }
      }

      list.add(srm);
    }
    return list;
  }

  /**
   * 返回指定类型的会话数据
   * @param sType
   * @return
   */
  public List<SysRunManage> getSessions(){
	  return getSessions(null);
  }
  
  public List<SysRunManage> getSessions(String sType){
    List<SysRunManage> list = new ArrayList<SysRunManage>();

    String response = this.fSHttpServiceImpl.sendPostRequest(this.url);
    if (!StringUtil.isEmpty(response)) {
      list = parseResponse(response);
      if (sType != null) {
        List<SysRunManage> r = new ArrayList<SysRunManage>();
        for (SysRunManage srm : list) {
          if (sType.equals(srm.getSessionType())) {
            r.add(srm);
          }
        }
        return r;
      }
      return list;
    }

    return list;
  }

  /***
   * 返回注册中心运行状态
   * @param list
   * @return
   */
  public boolean getIbmsStatus(String cmd){
	   return executeCmdServiceImpl.executeIbmsCmd(cmd);
  }

  public String getIbmsUrl(String url){
    return url;
  }

  
  @SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception{
	this.servletContext = dictDataServiceImpl.getServletContext();
	logger.info("初始化注册节点ip和port配置,servletContext:"+servletContext); 
	Map<String, Map<String, String>> dictMap = (Map<String, Map<String, String>>) servletContext.getAttribute("dictMap");
	
	this.ibms_ip = 		dictMap.get("http.ibms").get("ip");
    this.ibms_port = 	dictMap.get("http.ibms").get("port");
    this.ibms_session = dictMap.get("http.ibms").get("session");
    this.url = ("http://" + this.ibms_ip + ":" + this.ibms_port + "/" + this.ibms_session);
  }

}